package com.luo.demo.validation.config;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Spring Web验证器自定义国际化文件配置<br/>
 * 注：适用于Spring Boot 2.5.*
 *
 * @author luohq
 * @date 2022-05-21
 */
//@Configuration
public class WebValidationConfig implements WebMvcConfigurer {

    /**
     * 国际化消息源
     */
    private MessageSource messageSource;

    public WebValidationConfig(MessageSource messageSource) {
        //注入Spring Boot国际化消息源（需通过spring.messages明确指定）
        this.messageSource = messageSource;
    }

    /**
     * 使用自定义LocalValidatorFactoryBean，
     * 设置Spring国际化消息源
     */
    @Bean
    @Override
    public Validator getValidator() {
        LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
        //仅兼容Spring Boot spring.messages设置的国际化文件和原Hibernate的国际化文件
        //不支持resource/ValidationMessages.properties系列
        bean.setValidationMessageSource(this.messageSource);
        return bean;
    }

}